<template>
    <div>
      <!--   面包屑导航   -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!--   商品分类卡片   -->
      <el-card>
        <!-- 警告提示文案 -->
        <el-alert title="注意:只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>

        <!-- 选择商品分类区域-->
        <el-row>
          <el-col>
            <span>选择商品分类:</span>
            <!-- 选择商品分类的级联选择框-->
            <el-cascader expand-trigger="hover" @change="handleChange" clearable change-select-on v-model="value" :options="cateList" :props="cateProps"></el-cascader>
          </el-col>
        </el-row>

        <!-- Tabs 页签区域-->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- 添加动态参数的页面-->
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="cateCloseVisible = true">添加参数</el-button>
            <!-- 动态参数表格-->
            <el-table :data="manyTabData" border stripe>
              <!-- 展开航-->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 循环渲染tag标签-->
                  <el-tag closable :key="i" v-for="(item, i) in scope.row.attr_vals" @close="tagClose(scope,i)">{{item}}</el-tag>
                  <!-- 输入文本框-->
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                            ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope)" @blur="handleInputConfirm(scope)"></el-input>
                  <!-- 添加按钮-->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 索引列-->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="cateEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="cateDelete(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!-- 添加静态参数的页面-->
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="cateCloseVisible = true">添加属性</el-button>
            <!-- 静态参数表格-->
            <el-table :data="onlyTabData" border stripe>
              <!-- 展开航-->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!-- 循环渲染tag标签-->
                  <el-tag closable :key="i" v-for="(item, i) in scope.row.attr_vals" @close="tagClose(scope,i)">{{item}}</el-tag>
                  <!-- 输入文本框-->
                  <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                            ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope)" @blur="handleInputConfirm(scope)"></el-input>
                  <!-- 添加按钮-->
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!-- 索引列-->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="cateEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="cateDelete(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 添加动态参数对话框 -->
      <el-dialog :title="'添加'+titleText" :visible.sync="cateCloseVisible" width="50%" @close="cateFormClose">
        <el-form :model="cateForm" :rules="cateFormRules" ref="cateFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="cateForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cateCloseVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCateHandle">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改动态参数对话框 -->
      <el-dialog :title="'修改'+titleText" :visible.sync="editCloseVisible" width="50%" @close="editCateFormClose">
        <el-form :model="cateEditForm" :rules="cateEditFormRules" ref="cateEditFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="cateEditForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCloseVisible = false">取 消</el-button>
          <el-button type="primary" @click="cateEditHandle">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 联级选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 被选择中的商品
      value: [],
      // 被激活页签名称
      activeName: 'many',
      // 动态数据
      manyTabData: [],
      // 静态数据
      onlyTabData: [],
      // 控制添加框的显示与隐藏
      cateCloseVisible: false,
      // 添加动态参数
      cateForm: {
        attr_name: ''
      },
      // 添加表单验证对象
      cateFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      // 控制修改对话框的显示与隐藏
      editCloseVisible: false,
      // 修改表单数据
      cateEditForm: {
        attr_name: ''
      },
      // 修改表单数据验证规则
      cateEditFormRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      },
      // 控制文本插入框的显示与隐藏
      inputVisible: false,
      // 文本框的输入内容
      inputValue: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有的商品分类列表
    async getCateList() {
      const { data: result } = await this.$http.get('categories')
      if (result.meta.status !== 200) return this.$message.error('获取商品列表失败')
      this.cateList = result.data
    },
    // 级联选择框变化触发
    handleChange() {
      this.getParams()
    },
    // Tab点击事件
    handleClick() {
      this.getParams()
    },
    // 获取参数的列表数据
    async getParams() {
      // 判断是否为三级菜单
      if (this.value.length !== 3) {
        this.value = []
        this.manyTabData = []
        this.onlyTabData = []
        this.$message.error('只允许为第三级分类设置相关参数')
      }

      // 是三级菜单执行
      const { data: result } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (result.meta.status !== 200) return console.log(`获取${this.activeName}数据失败`)

      result.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框的值
        item.inputValue = ''
      })

      // 判断数据为静态还是动态
      if (this.activeName === 'many') {
        this.manyTabData = result.data
      } else {
        this.onlyTabData = result.data
      }
    },
    // 监听添加对话框关闭事件
    cateFormClose() {
      this.$refs.cateFormRef.resetFields()
    },
    // 发起添加属性
    addCateHandle() {
      this.$refs.cateFormRef.validate(async valid => {
        if (!valid) return console.log('添加失败')
        const { data: result } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.cateForm.attr_name,
          attr_sel: this.activeName
        })
        if (result.meta.status !== 201) return this.$message.error('添加参数失败!')
        this.$message.success('添加参数成功!')
        this.cateCloseVisible = false
        this.getParams()
      })
    },
    // 修改对话框，显示
    async cateEditDialog(attrId) {
      this.attrId = attrId
      const { data: result } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { params: { attr_sel: this.activeName } })
      if (result.meta.status !== 200) return
      this.cateEditForm = result.data
      this.editCloseVisible = true
    },
    // 修改请求发起
    cateEditHandle() {
      this.$refs.cateEditFormRef.validate(async valid => {
        if (!valid) return
        const { data: result } = await this.$http.put(`categories/${this.cateId}/attributes/${this.cateEditForm.attr_id}`, {
          attr_sel: this.activeName,
          attr_name: this.cateEditForm.attr_name
        })
        if (result.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editCloseVisible = false
        this.getParams()
      })
    },
    // 监听修改对话框关闭事件
    editCateFormClose() {
      this.$refs.cateEditFormRef.resetFields()
    },
    // 删除动态参数静态属性 请求
    cateDelete(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: result } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (result.meta.status !== 200) return
        this.getParams()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 文本框失去焦点或按下enter键
    handleInputConfirm(scope) {
      if (scope.row.inputValue.trim().length === 0) {
        scope.row.inputValue = ''
        scope.row.inputVisible = false
      }
      // 如果没有return 则证明输入内容，需要做后续的处理
      scope.row.attr_vals.push(scope.row.inputValue.trim())
      scope.row.inputValue = ''
      scope.row.inputVisible = false

      // 调用saveAttrVals
      this.saveAttrVals(scope)
    },
    // 将对attr_vals的操作保存到数据库
    async saveAttrVals(scope) {
      // 需要发起请求，保存此次操作
      const { data: result } = await this.$http.put(`categories/${this.cateId}/attributes/${scope.row.attr_id}`, {
        attr_name: scope.row.attr_name,
        attr_sel: scope.row.attr_sel,
        attr_vals: scope.row.attr_vals.join(' ')
      })
      if (result.meta.status !== 200) return this.$message.error('添加失败')
    },
    // 点击按钮展示文本框
    showInput(scope) {
      scope.row.inputVisible = true
      // 让文本框自动获取焦点
      // $nextTick方法的作用，就是当页面上元素被重新渲染才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 点击删除tag事件
    tagClose(scope, i) {
      scope.row.attr_vals.splice(i, 1)
      this.saveAttrVals(scope)
    }
  },
  computed: {
    // 如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled() {
      if (this.value.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 当前选中的三级分类id
    cateId() {
      if (this.value.length === 3) {
        return this.value[2]
      } else {
        return null
      }
    },
    // 动态计算标题text
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    }
  }
}

</script>

<style scoped lang="less">
span {
  padding-right: 15px;
}
.el-alert {
  margin-bottom: 10px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 100px;
}
</style>
